package com.os.interceptor;

import com.os.core.common.JsonResult;
import com.os.core.common.ResultCode;
import com.os.utils.JsonUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author Matt
 * @Date 2022-01-09
 * @Desc:
 * @Version 1.0
 */
public class OneInterceptor implements HandlerInterceptor {

    /**
     * 在请求之前进行调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        if(true){
            returnErrorResponse(httpServletResponse, JsonResult.returnResponse(true, ResultCode.ACCESS_ERROR, "被one拦截了。。。"));
        }
        System.out.println("被one拦截了。。。");
        return false;
    }

    /**
     * 在请求之后进行调用，但是在试图渲染之前（controller方法调用之后）
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 在请求结束之后被调用，也就是在DispatcherServlet渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

    public void returnErrorResponse(HttpServletResponse response, JsonResult jsonResult) throws IOException {
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(jsonResult).getBytes("utf-8"));
            out.flush();
        } finally {
            if(out != null){
                out.close();
            }
        }
    }

}
